package com.example.sportrecord.SQL;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.sportrecord.R;

import java.util.ArrayList;

import static java.lang.String.valueOf;

public class LinearAdapter extends RecyclerView.Adapter <LinearAdapter.LinearViewHolder> {
    ArrayList<User> list;
    Context context;
    private View inflater;
    public LinearAdapter(Context context,ArrayList<User> list) {
        this.context=context;
        this.list=list;
    }

    @NonNull
    @Override
    public LinearViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        inflater= LayoutInflater.from(context).inflate(R.layout.item,parent,false);
        LinearViewHolder linearViewHolder=new LinearViewHolder(inflater);
        return linearViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull final LinearViewHolder holder, final int position) {
        User user=(User)list.get(position);
            holder.record_date.setText(user.getDate());
            holder.start_time.setText(user.getStartTime());
            holder.stop_time.setText(user.getStopTime());
            holder.all_time.setText(user.getAll_usetime());
            holder.explains.setText(user.getExplain1());

            holder.delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String timeIn = holder.stop_time.getText().toString();
                SQLOperation sqlOperation1 = new SQLOperation(context);
                sqlOperation1.deletOneData(timeIn);
                Toast.makeText(context,"删除"+timeIn+"成功",Toast.LENGTH_LONG).show();
                list.remove(getItem(position));
                notifyDataSetChanged();//刷新删除后的数据
            }
        });
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    public User getItem(int position) {
        return list.get(position);
    }


    @Override
    public int getItemCount() {
        return list.size();
    }

    class  LinearViewHolder extends RecyclerView.ViewHolder {
       TextView record_date,start_time,stop_time,all_time,explains;
       Button delete;
        public LinearViewHolder(@NonNull View itemView) {
            super(itemView);
            record_date=itemView.findViewById(R.id.record_date);
            start_time=itemView.findViewById(R.id.start_time);
            stop_time=itemView.findViewById(R.id.stop_time);
            all_time=itemView.findViewById(R.id.all_time);
            explains=itemView.findViewById(R.id.explains);

            delete = itemView.findViewById(R.id.delete);
        }
    }
}
